let tableTitle = $("#tableTitle");

// Pagination variables
let firstPageIndex = 1;
let lastPageIndex = -1;

let msg = $("#msg");
let pagination = $("#pagination");

console.log("Current page index: " + parseInt($(".page-item.active").text()));

tableTitle.text("Customer");

init();

// Pagination
pagination.on("click", ".page-item", function () {
    console.log("page-item click...");
    let _this = $(this);
    if (_this.attr("class") === "page-item active" || _this.hasClass("disabled")) {
        return;
    }

    let clickPageItemId = _this.attr("id");
    let currentPageItem = $(".page-item.active");
    let cpi = $("#currentPageIndex");
    let currentPageIndex = parseInt(cpi.text());
    let previous = $("#previous");
    let next = $("#next");
    let pageItemId = "";

    currentPageItem.attr("class", "page-item");

    // Set currentPageIndex
    if (clickPageItemId === "previous" && currentPageIndex > 1) {
        // -1
        cpi.text(currentPageIndex - 1);
        if (parseInt(cpi.text()) <= 3) {
            pageItemId = "page-" + parseInt(cpi.text());
            $("#" + pageItemId).attr("class", "page-item active");
        }
    } else if (clickPageItemId === "next" && currentPageIndex < lastPageIndex) {
        // +1
        cpi.text(currentPageIndex + 1);
        if (parseInt(cpi.text()) <= 3) {
            pageItemId = "page-" + parseInt(cpi.text());
            $("#" + pageItemId).attr("class", "page-item active");
        }
    } else {
        _this.attr("class", "page-item active");
        cpi.text(parseInt(_this.text()));
    }

    // Set previous or next
    if (parseInt(cpi.text()) === firstPageIndex) {
        previous.attr("class", "page-item disabled");
        next.attr("class", "page-item");
    } else if (parseInt(cpi.text()) === lastPageIndex) {
        previous.attr("class", "page-item");
        next.attr("class", "page-item disabled");
    } else {
        previous.attr("class", "page-item");
        next.attr("class", "page-item");
    }


    // Reset && Remove tbody
    $("tbody").remove();

    // Retrieve
    $.ajax({
        async: true,
        crossDomain: true,
        // Hava two args: page and size
        url: "/customer?page=" + parseInt(cpi.text()) + "&size=" + 5,
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            "cache-control": "no-cache",
            "Author": "hsowan"
        },
        processData: false,
        success: function (res) {
            if (res.success === true) {
                let customers = res.content;
                let customerTable = $("#customerTable");
                let s = "";
                console.log(customers);
                for (let i = 0; i < customers.length; i++) {
                    s = "<tbody><tr><td>" +
                        customers[i].id + "</td><td>" +
                        customers[i].createTime + "</td><td>" +
                        customers[i].username + "</td><td>" +
                        customers[i].password + "</td><td>" +
                        customers[i].age + "</td>" +
                        "<td><a href=\"javascript:void(0)\" id=\"deleteCustomer\" data-toggle=\"modal\" data-target=\"#deleteModal\"><span class=\"oi oi-trash\" title=\"Delete\" aria-hidden=\"true\"></span></a> | <a href=\"javascript:void(0)\" id=\"updateCustomer\" data-toggle=\"modal\" data-target=\"#addOrUpdateCustomerModal\"><span class=\"oi oi-pencil\" title=\"Update\" aria-hidden=\"true\"></span></a></td></tr></tbody>";
                    customerTable.append(s);
                }
                showMsg("alert-success", 3000, res.message);
            } else {
                showMsg("alert-warning", 3000, res.message);
            }
        }
    });
});


// Delete customer
$(document).ready(
    function () {
        $("#customerTable").on("click", "#deleteCustomer", function () {
                // Get customer id
                let customerId = parseInt($(this).parent().siblings().first().text());
                $("#confirmDeleteCustomer").click(
                    function () {
                        console.log("Delete customer has been confirmed...");
                        $.ajax({
                            async: true,
                            crossDomain: true,
                            // Have two args: page and size
                            url: "/customer/" + customerId,
                            method: "DELETE",
                            headers: {
                                "Content-Type": "application/json",
                                "cache-control": "no-cache",
                                "Author": "hsowan"
                            },
                            processData: false,
                            success: function (res) {
                                if (res.success === true) {
                                    init();
                                    showMsg("alert-success", 3000, res.message);
                                } else {
                                    showMsg("alert-warning", 3000, res.message);
                                }
                            }
                        })

                    }
                );
                $("#closeDeleteCustomerModal").click();
            }
        );
    }
);

// Add customer
$(document).ready(function () {
    $("#addCustomer").click(function () {
        $("#addOrUpdateCustomerLabel").text("Add customer");
        $("#confirmAddOrUpdateCustomer").click(function () {
            let data = {
                "username": $("#username").val(),
                "password": $("#password").val(),
                "age": $("#age").val()
            };
            $.ajax({
                async: true,
                crossDomain: true,
                url: "/customer",
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "cache-control": "no-cache",
                    "Author": "hsowan"
                },
                processData: false,
                // string -> json
                data: JSON.stringify(data),
                success: function (res) {
                    if (res.success === true) {
                        init();
                        showMsg("alert-success", 3000, res.message);
                    } else {
                        showMsg("alert-warning", 3000, res.message);
                    }
                }
            });
            $("#closeAddCustomerModal").click();
        });
    });
});


// Update customer
$(document).ready(function () {
    $("#customerTable").on("click", "#updateCustomer", function () {
        let customerId = parseInt($(this).parent().siblings().first().text());
        $("#addOrUpdateCustomerLabel").text("Update customer");

        $.ajax({
            async: true,
            crossDomain: true,
            url: "/customer/" + customerId,
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "cache-control": "no-cache",
                "Author": "hsowan"
            },
            success: function (res) {
                if (res.success === true) {
                    $("#username").val(res.content.username);
                    $("#password").val(res.content.password);
                    $("#age").val(res.content.age);
                    showMsg("alert-success", 3000, res.message);
                } else {
                    showMsg("alert-warning", 3000, res.message);
                }
            }
        });
        $("#confirmAddOrUpdateCustomer").click(function () {
            let data = {
                "id": customerId,
                "username": $("#username").val(),
                "password": $("#password").val(),
                "age": $("#age").val()
            };
            $.ajax({
                async: true,
                crossDomain: true,
                url: "/customer",
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "cache-control": "no-cache",
                    "Author": "hsowan"
                },
                processData: false,
                // string -> json
                data: JSON.stringify(data),
                success: function (res) {
                    if (res.success === true) {
                        init();
                        showMsg("alert-success", 3000, res.message);
                    } else {
                        showMsg("alert-warning", 3000, res.message);
                    }
                }
            });
            $("#closeAddCustomerModal").click();
        });
    });
});

$(document).ready(
    function () {
        $(".close").click(
            function () {
                console.log("Clear closed modal values");
                $("#username").val("");
                $("#password").val("");
                $("#age").val("");
            }
        );
    }
);

function showMsg(type, time, message) {
    msg.addClass(type);
    msg.text(message);
    msg.show();
    setTimeout(function () {
        msg.removeClass(type);
        msg.hide();
    }, time);
}

function init() {
    $("tbody").remove();
    $(".pagination").remove();

    // Init pagination
    $(document).ready(
        function () {
            $.ajax({
                async: true,
                crossDomain: true,
                url: "/customer/count",
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    "cache-control": "no-cache",
                    "Author": "hsowan"
                },
                processData: false,
                success: function (res) {
                    if (res.success === true) {
                        console.log(res.message);
                        let count = res.content;
                        let a = count / 5;
                        let b = parseInt(count / 5);
                        if (a === b) {
                            lastPageIndex = b;
                        } else {
                            lastPageIndex = b + 1;
                        }

                        if (lastPageIndex >= 1) {
                            $("#currentPageIndex").text(1);
                        } else {
                            $("#currentPageIndex").text(0);
                        }

                        // show count at frontend
                        $("#getCount").text(count);

                        // Set pagination

                        pagination.append("<ul class=\"pagination\"></ul>")
                        let p = $(".pagination");
                        p.append("<li class=\"page-item disabled\" id=\"previous\"><a class=\"page-link\" href=\"javascript:void(0)\" tabindex=\"-1\">Previous</a></li>");

                        if (lastPageIndex <= 3) {
                            for (let i = 1; i <= lastPageIndex; i++) {
                                if (i === 1) {
                                    // First page
                                    p.append("<li class=\"page-item active\" id=\"page-" + i + "\"><a class=\"page-link\" href=\"javascript:void(0)\">" + i + "</a></li>");
                                } else {
                                    p.append("<li class=\"page-item\" id=\"page-" + i + "\"><a class=\"page-link\" href=\"javascript:void(0)\">" + i + "</a></li>");
                                }
                            }
                        } else {
                            for (let i = 1; i <= 3; i++) {
                                if (i === 1) {
                                    // First page
                                    p.append("<li class=\"page-item active\" id=\"page-" + i + "\"><a class=\"page-link\" href=\"javascript:void(0)\">" + i + "</a></li>")
                                } else {
                                    p.append("<li class=\"page-item\" id=\"page-" + i + "\"><a class=\"page-link\" href=\"javascript:void(0)\">" + i + "</a></li>");
                                }
                            }
                            // more -> ...
                            p.append("<li class=\"page-item disabled\" id=\"more\"><a class=\"page-link\" href=\"javascript:void(0)\">...</a></li>");
                        }
                        p.append("<li class=\"page-item\" id=\"next\"><a class=\"page-link\" href=\"javascript:void(0)\">Next</a></li>");

                        console.log("listCustomer click...");
                        $("#listCustomers").click();
                    } else {
                        showMsg("alert-warning", 3000, res.message);
                        $("#getCount").text(0);
                    }
                }
            });
        }
    );

    // List customers
    $("#listCustomers").click(
        function () {
            console.log("listCustomer click...");
            tableTitle.text("Customer");

            $.ajax({
                async: true,
                crossDomain: true,
                // Have two args: page and size
                url: "/customer?page=" + parseInt($("#currentPageIndex").text()) + "&size=" + 5,
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    "cache-control": "no-cache",
                    "Author": "hsowan"
                },
                processData: false,
                success: function (res) {
                    if (res.success === true) {
                        // Remove tbody
                        $("tbody").remove();

                        console.log(res);
                        let customers = res.content;
                        let customerTable = $("#customerTable");
                        let s = "";
                        console.log(customers);
                        for (let i = 0; i < customers.length; i++) {
                            s = "<tbody><tr><td>" +
                                customers[i].id + "</td><td>" +
                                customers[i].createTime + "</td><td>" +
                                customers[i].username + "</td><td>" +
                                customers[i].password + "</td><td>" +
                                customers[i].age + "</td>" +
                                "<td><a href=\"javascript:void(0)\" id=\"deleteCustomer\" data-toggle=\"modal\" data-target=\"#deleteModal\"><span class=\"oi oi-trash\" title=\"Delete\" aria-hidden=\"true\"></span></a> | <a href=\"javascript:void(0)\" id=\"updateCustomer\" data-toggle=\"modal\" data-target=\"#addOrUpdateCustomerModal\"><span class=\"oi oi-pencil\" title=\"Update\" aria-hidden=\"true\"></span></a></td></tr></tbody>";
                            customerTable.append(s);
                        }
                        showMsg("alert-success", 3000, res.message);
                    } else {
                        showMsg("alert-warning", 3000, res.message);
                    }
                }
            });
        }
    );
}
